package com.ttc.mBackup.BackupAgent;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;

import com.ttc.mBackup.BackupActivity;
import com.ttc.mBackup.R;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class BARSelector extends Activity {

	/*
	 * Define Widget 
	 */
	TextView tilte;
	ListView list;
	Button cont,cancel;
	ArrayAdapter<String> adapter = null;
	ArrayList<String> model = new ArrayList<String>();
	ArrayList<String> listSys = new ArrayList<String>();
	
	public final static String KEY_ELEMENT_SYSTEM="element";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.progresslayout);
		
		/*
		 * Get extra from intent which send by BARLocation*/
		final Bundle data = getIntent().getExtras();
		
		/*Get ID of widget*/
		tilte = (TextView) findViewById(R.id.task_label);
		list =(ListView) findViewById(R.id.task_list);
		cont = (Button) findViewById(R.id.Cont_btn);
		cont.setVisibility(2);
		
		cancel = (Button) findViewById(R.id.Cancle_btn);
		model.add("System Setting");
		cancel.setVisibility(2);
		LinearLayout line = (LinearLayout) findViewById(R.id.laylinear);
		line.setVisibility(2);
		
		if(data!=null)
		{
			/*Set lable depend on Boolean value from data */
			listSystem(data.getBoolean(BackupActivity.KEY_ACTIVITY),
					   data.getString(BARLocaltion.DIR_CHOICE)
					   ,data.getString("FILE_NAME")
					   ,data.getBoolean(BARLocaltion.CLOUD_STORE));
			
			
				tilte.setText(data.getBoolean(BackupActivity.KEY_ACTIVITY)?
						"Select what you want to backup":
							"Select what you want to restore");
			
			
				
			/*Create ClickListener  for cont*/
			cont.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
			/*
			 * Call Activity PerformTaskt and wait to recieve result of this Activity
			 * */
				
				Intent i = new Intent("com.ttc.mBackup.BackupAgent.PERFORMTASK");
				
				if(list.isItemChecked(0)){
					listSys=model;
					listSys.remove(0);
				}
				if(listSys.size()>0){
					data.putStringArrayList(KEY_ELEMENT_SYSTEM, listSys);
				
				i.putExtras(data);
				startActivityForResult(i,1);
				}
				else{
					Toast tost = Toast.makeText(BARSelector.this, "Please Choice a Systems Setting", Toast.LENGTH_LONG);
					tost.setGravity(Gravity.CENTER,0, 0);
					tost.show();
				}
				}
			});
			
		}
	
		list.setChoiceMode(2);//Set multichoice for listview
		/*Create Adapter for listview*/
		adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice,model);
		list.setItemChecked(0, true);
		/*Set Adapter for listview*/
		list.setOnItemClickListener(new OnItemClickListener()
		{

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				if(arg2==0)
				{
					checkall(list.isItemChecked(0));
				}
				
				if(list.isItemChecked(arg2)&&arg2!=0)
				{
					listSys.add(model.get(arg2));
				}
				else
				{
					if(listSys.contains(model.get(arg2)))
					{
						listSys.remove(model.get(arg2));
					}
				}
				
			}});
		list.setTextFilterEnabled(true);
		list.setAdapter(adapter);
		/*
		 * Set onclickListner for Button Cancle
		 */
		
		cancel.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
			/*End this Activity*/
				finish();
			}
		});
		
	}
	/*
	 * Method Recieve result from PerformTask
	 * */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if(requestCode==1)
		{
			if(resultCode==RESULT_OK)
			{
				/*Set result*/
				setResult(2, data);
				/*Call back PerformTask to show everything done*/
				Intent i = new Intent("com.ttc.mBackup.BackupAgent.PERFORMTASK");
				i.putExtra("DONE", true);
				startActivity(i);
				
			}
			finish();
		}
	}

	/*Set model of Listview*/
	private void listSystem(boolean task,String dir,String name,boolean Cloud)
	{
		   DBAdapter da=null;
		   Cursor db=null;
		if(task){
		Uri allSystem = Settings.System.CONTENT_URI;
		 db  = managedQuery(allSystem, null, null, null, null);
	
		}
		else
		{
			if(!Cloud){try {
	            // Make sure the Pictures directory exists.
	            ///File Doc
				  InputStream is = new FileInputStream(new File(dir + File.separator+name));
	            //File ghi
	            OutputStream os = new FileOutputStream( new File("data/data/com.ttc.mBackup/databases/"+DBAdapter.DATABASE_NAME));
	            byte[] data = new byte[is.available()];
	            is.read(data);
	            os.write(data);
	            is.close();
	            os.close();
	        } catch (IOException e) {
	            // Unable to create file, likely because external storage is
	            // not currently mounted.
	            Log.w("ExternalStorage", "Error writing " + new File(dir + File.separator+name), e);
	        }
	        }
	     da=new DBAdapter(BARSelector.this);
	       da.open();
	        db =da.getAllValue();
	      
	       
		}
		 if(db.moveToFirst())
	       {
	    	   do
	    	   {
	    		   
	    		   model.add(db.getString(1));
	    		   
	    	   }while(db.moveToNext());
	       }
	       
	 if(da!=null)
{
		 da.close();
		 if(!Cloud){ new File("data/data/com.ttc.mBackup/databases/"+DBAdapter.DATABASE_NAME).delete();}}	
	}
	
	private void checkall(boolean check)
	{
		for(int i=0;i<model.size()-1;i++)
		{
			list.setItemChecked(i+1, check);
		}
	}
}
